import {
  getDelayProcessById,
  ossDownload
} from '/service/service'
const {
  getCurrentStatusMap
} = require('/utils/statusMap')
Component({
  mixins: [],
  data: {
    list: []
  },
  props: {
    id: {
      type: 'string',
      default: ''
    }
  },
  didMount() {
    this.getList()
  },
  didUpdate() {},
  didUnmount() {},
  methods: {
    async getList() {
      try {
        const res = await getDelayProcessById({
          workOrderId: this.props.id
        });

        const newList = await Promise.all(
          res.map(async (item) => {
            let imgList = [];
            if (item.operationName === '延期申请' && Array.isArray(item.attachments) && item.attachments.length > 0) {
              // 4. 并行调用 ossDownload，提升加载速度（替换串行 for 循环）
              imgList = await Promise.all(
                item.attachments.map(async (s) => {
                  // 5. 对 ossId 做空值校验，避免无效请求
                  if (!s.ossId) return null;
                  try {
                    const ossPath = await ossDownload(s.ossId);
                    return {
                      ...s,
                      ossPath
                    };
                  } catch (ossErr) {
                    console.warn('附件下载失败：', ossErr);
                    return null; // 单个附件失败不影响整体
                  }
                })
              ).then(imgs => imgs.filter(Boolean)); // 过滤下载失败的附件
            }

            return {
              ...item,
              imgList: imgList || [],
              currentStatusName: getCurrentStatusMap(item.status) || '未知状态'
            };
          })
        );

        this.setData({
          list: newList,
        });
      } catch (e) {

        const errorMsg = e.message ? e.message : '数据加载失败，请稍后重试'
        my.alert({
          content: errorMsg
        })
        console.error('延期流程列表加载失败：', e);
      }
    },
    async imagePreview(e) {
      const {
        url
      } = e.currentTarget.dataset

      this.previewSingleImage(url)
    },
    previewSingleImage(url) {
      dd.previewImage({
        urls: [url],
        current: url,
        success: () => {
          console.log('图片预览成功');
        },
        fail: (err) => {
          console.error('图片预览失败', err);
          dd.showToast({
            content: '预览失败，请重试',
            type: 'fail',
            duration: 2000
          });
        }
      });
    },
  },
});